import javax.swing.*;
import java.util.ArrayList;
import java.util.List;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import Back.CarPathInfo;
import Dao.*;
import redis.clients.jedis.resps.Tuple;

public class MainApp extends JFrame {

    public MainApp() {
        // 设置窗口属性
        super("实时地图");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(800, 800);
        setLayout(null);

        RedisRepository redisRepo = new RedisRepository("localhost", 6379);
        MapService mapService = new MapService(redisRepo);

        // 创建地图面板，并设置其位置和大小，留出一部分给按钮
        int panelHeight = getHeight() - 60; // 留出60像素给按钮
        MapPanel mapPanel = new MapPanel(mapService);
        mapPanel.setBounds(0, 0, getWidth(), panelHeight);  // 设置地图面板的高度
        add(mapPanel);

        // 创建保存按钮
        JButton saveButton = new JButton("保存回放数据");
        int buttonWidth = 200;  // 设定按钮宽度为200
        int buttonHeight = 35;  // 设定按钮高度为40
        saveButton.setBounds((getWidth() - buttonWidth) / 2, getHeight() - buttonHeight-30, buttonWidth, buttonHeight); // 设置按钮在底部居中，并且上下间隔10像素
        saveButton.addActionListener(e -> {
            RedisRepository.MapData data = mapService.getCurrentMapData();
            dt dao = new dt();
            dao.connect();
            SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
            String timestamp = sdf.format(new Date());
            String replayName = "Replay_" + timestamp;
            int height = data.height;
            int width = data.width;
            int count = data.count;
            double global_time = 0;
            String map = redisRepo.getstaticmap();

            List<CarPathInfo> carPaths = new ArrayList<>();
            for (int i = 1; i <= count; i++) {
                List<Tuple> path = redisRepo.getcarpath(String.valueOf(i));
                StringBuilder pathBuilder = new StringBuilder();

                if (path != null) {
                    for (Tuple tuple : path) {
                        String member = tuple.getElement();
                        double score = tuple.getScore();
                        global_time = Math.max(global_time, score);

                        if (pathBuilder.length() > 0) {
                            pathBuilder.append("+");
                        }
                        pathBuilder.append(score).append(":").append(member);
                    }
                }
                carPaths.add(new CarPathInfo(i, pathBuilder.toString()));
            }

            dao.insert(replayName, width, height, map, count, (int) global_time);
            for (CarPathInfo info : carPaths) {
                dao.addcar(replayName, info.carId, info.path);
            }
            System.out.println("✅ 保存回放数据按钮被点击");
            dao.closeConnection();
        });

        add(saveButton);

        // 定时更新地图
        Executors.newScheduledThreadPool(1).scheduleAtFixedRate(() -> {
            SwingUtilities.invokeLater(() -> {
                mapPanel.repaint();
            });
        }, 0, 16, TimeUnit.MILLISECONDS);
    }

    public static void main(String[] args) {
        // 创建并显示窗口
        SwingUtilities.invokeLater(() -> {
            MainApp app = new MainApp();
            app.setVisible(true);
        });
    }
}
